import { monStorage, Storage } from 'clientConfig/util/StoreData';
import { NEW, RUNNING, TERMINATED, COMPLETED, CANCELED } from 'clientConfig/constants'
import urllist from 'clientConfig/urllist';
const net = require('clientConfig/util/net');
const DB = require('app/db');
function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}
function JudgeQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return true; return null;
}
function getObjectValue(obj) {
    if (obj != undefined) {
        if (typeof (obj) == "object") {
            if (JSON.stringify(obj) == "{}") {
                return '';
            } else {
                return JSON.stringify(obj);
            }
        } else {
            return obj;
        }
    } else {
        return '';
    }
}
function updateSession(cb) {
    var unionid = Storage.get('user.unionid');
    if (unionid) {
        let type = window.type;
        let name = monStorage.get('user.nickname')
        let email = monStorage.get('user.email')
        let avatar = monStorage.get('user.avatar')
        let unionid = Storage.get('user.unionid')
        let corp_name = monStorage.get('user.corp_name')
        let auth_level = monStorage.get('user.auth_level')
        let url = urllist.getInfoById + '?type=' + type + '&id=' + unionid;
        net.fetchUrl(url, { method: "post", body: { name, email, avatar, unionid } }).then((result) => {
            if (!result) return;
            if (result.errcode == 0) {
                //  alert(result.session)
                monStorage.set('user.session', result.session);
                Storage.set('user.info', result);
                cb && cb();
            }
        });
    }
}
function loopSession() {

    let interval_id = setInterval(() => {
        var unionid = Storage.get('user.unionid');
        //console.log(new Date().toLocaleString())
        if (unionid) {
            let type = window.type;
            let name = monStorage.get('user.nickname')
            let email = monStorage.get('user.email')
            let avatar = monStorage.get('user.avatar')
            let unionid = Storage.get('user.unionid')
            let corp_name = monStorage.get('user.corp_name')
            let auth_level = monStorage.get('user.auth_level')
            let url = urllist.getInfoById + '?type=' + type + '&id=' + unionid;
            net.fetchUrl(url, { method: "post", body: { name, email, avatar, unionid, corp_name, auth_level } }).then((result) => {
                if (!result) {
                    clearInterval(interval_id);
                    loopSession();
                }
                if (result.errcode == 0) {
                    //  alert(result.session)
                    //console.log(result.session)
                    monStorage.set('user.session', result.session);
                    Storage.set('user.info', result);
                }
            });
        }
    }, 1000 * 60 * 2.9);

}
function order(a, b) {
    return (a.value - b.value)
}
function guid() {
    function S4() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    }
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}
function getTime() {
    let date_obj = new Date();
    const sup = (n) => { return (n < 10) ? '0' + n : n; }
    var date = (date_obj.getFullYear()
        + "-" + sup(date_obj.getMonth() + 1)
        + "-" + sup(date_obj.getDate())
        + " " + sup(date_obj.getHours())
        + ":" + sup(date_obj.getMinutes())
        + ":" + sup(date_obj.getSeconds())).replace(/\-/g, "\/");
    return date;
}
function getIntervalTime(utc) {
    let day = Math.floor(utc / (24 * 60 * 60 * 1000));//天
    utc = utc % (24 * 60 * 60 * 1000);
    let hour = Math.floor(utc / (60 * 60 * 1000));//小时
    utc = utc % (60 * 60 * 1000);
    let minute = Math.floor(utc / (60 * 1000));//分
    utc = utc % (60 * 60 * 1000);
    return day > 0 ? day + '天' + hour + '小时' + minute + '分' : (hour > 0 ? hour + '小时' + minute + '分' : minute + '分')
}
//change-变更申请 update-审批消息
function getMarkdownText({ old_change = [], new_change = [], change_type = undefined, toApprovers = [], create_time, originator_user, approvers, proj_name, proj_num, status, process_result = undefined, title = "" } = {}, type = undefined) {
    if (!create_time || !originator_user || !proj_name || !proj_num || !status) {
        console.log("参数不全")
        return;
    }
    if (status == NEW) {
        var text = '待审批'
        var color = '#EFAA33'
    } else if (status == RUNNING) {
        var text = '审批流转中'
        var color = '#EFAA33'
    } else if (status == TERMINATED) {
        var text = '审批拒绝'
        var color = '#E92C2C'
    } else if (status == COMPLETED) {
        var text = '审批通过'
        var color = '#17C295'
    } else if (status == CANCELED) {
        var text = '审批撤销'
        var color = '#B3B3B3'
    }
    var $approversStr = '';
    approvers = approvers instanceof Array ?
        approvers :
        [approvers];
    approvers.map((item, index) => {
        $approversStr += ` \n+ 审批人 ${item}`
    })
    var $toApproversStr = '';
    toApprovers.map((item, index) => {
        $toApproversStr += ` \n+ 待审批人 ${item}`
    })
    if (!type) {
        return `### 有新的审批提醒 \n> **◆${title}** \n+ ${create_time}  \n+ 发起人 ${originator_user} ${$approversStr} ${$toApproversStr} \n+ ${proj_name} \n+ 项目编号：${proj_num} \n+ <font color=${color} >${text}</font> `
    } else if (type == "update") {
        let content = `### 有新的审批提醒\n> **◆${title}** \n+ ${create_time}  \n+ 发起人 ${originator_user} ${$approversStr} ${$toApproversStr} \n+ ${proj_name} \n+ 项目编号：${proj_num} \n+ <font color=${color} >${text}</font> \n `
        if (process_result)
            content += `+ 意见:${process_result} `;
        return content;
    } else if (type == "change") {
        let content = `### 有新的审批提醒\n> **◆${title}** \n+ ${create_time} \n+ 发起人 ${originator_user} ${$approversStr} ${$toApproversStr} \n+ ${proj_name} \n+ 项目编号：${proj_num} \n+ <font color=${color} >${text}</font> \n `
        if (new_change.length > 0 && old_change.length > 0) {
            // let old = "";
            // for(let i=0;i<old_change.length;i++){
            //     let old
            // }
            content += `+ 发起变更申请 \n+ 变更类型:${change_type}`;
        }
        if (change_type == "撤销申请") {
            content += `+ 发起变更申请 \n+ 变更类型:${change_type}`;
        }
        return content;
    }
}
function sendNotice(noticed_lists, params) {
    let content = {
        notice_id: guid(),//通知消息id
        time: getTime(),//消息时间
        no_read: false,//是否已读,true已读,false未读
        notice_content: params
    }
    DB.Notice.send_notice.config.query = {
        mes_receiver_list: noticed_lists
    };
    DB.Notice.send_notice(content)
        .then((content) => {
            if (!content) {
                console.log('成功')
            } else {
                console.log('失败')
            }
        })
        .catch((error) => {

        });
}
//数组合并并去重
function mergeArray(arr1, arr2) {
    for (var i = 0; i < arr1.length; i++) {
        for (var j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j]) {
                arr1.splice(i, 1); //利用splice函数删除元素，从第i个位置，截取长度为1的元素
            }
        }
    }
    for (var i = 0; i < arr2.length; i++) {
        arr1.push(arr2[i]);
    }
    return arr1;
}
//兼容安卓的时间显示
function dealTime(time) {
    if (typeof time != 'number') { console.log('时间不对'); return; }
    if (navigator.userAgent.indexOf('iPhone') != -1) {
        return new Date(time).toLocaleDateString();
    } else if (navigator.userAgent.indexOf('Android') != -1) {
        let data = new Date(time).toJSON();
        data = data.substr(0, 10);
        return data.replace(/\-/g, '\/');
    } else {
        return new Date(time).toLocaleDateString();
    }
}
export { GetQueryString, JudgeQueryString, getObjectValue, updateSession, loopSession, guid, getTime, getIntervalTime, getMarkdownText, sendNotice, mergeArray, order, dealTime }